<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="学校名称" prop="schoolName">
        <el-input
            v-model="queryParams.schoolName"
            placeholder="请输入学校名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校类型" prop="schoolType">
        <el-input
            v-model="queryParams.schoolType"
            placeholder="请输入学校类型"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校地址" prop="schoolLocation">
        <el-input
            v-model="queryParams.schoolLocation"
            placeholder="请输入学校地址"
            clearable
            style="width: 240px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:school:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:school:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:school:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['system:school:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:school:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="schoolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学校编号" prop="id" width="120" />
      <el-table-column label="学校名称" prop="schoolName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="学校类型" prop="schoolType" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="学校地址" prop="schoolLocation" width="100" />
      <el-table-column label="学校风景" prop="sceneryImages" width="100">
        <template #default="scope">
          <div>
            <!-- 统一处理图片数据为数组格式 -->
            <template v-if="formatImages(scope.row.sceneryImages).length > 0">
              <el-image
                  v-for="(img, index) in formatImages(scope.row.sceneryImages)"
                  :key="index"
                  style="width: 100px; height: 100px; margin-right: 5px"
                  :src="getImageUrl(img)"
                  :preview-src-list="formatImages(scope.row.sceneryImages).map(img => getImageUrl(img))"
                  :initial-index="index"
                  fit="cover"
                  hide-on-click-modal
              />
            </template>
            <span v-else>暂无图片</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top" v-if="scope.row.id !== 1">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:school:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.id !== 1">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:school:remove']"></el-button>
          </el-tooltip>
          <el-tooltip content="数据权限" placement="top" v-if="scope.row.id !== 1">
            <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(scope.row)" v-hasPermi="['system:school:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="分配用户" placement="top" v-if="scope.row.id !== 1">
            <el-button link type="primary" icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:school:edit']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改学校配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="schoolRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model="form.schoolName" placeholder="请输入学校名称" />
        </el-form-item>
        <el-form-item label="学校类型" prop="schoolType">
          <el-input v-model="form.schoolType" placeholder="请输入学校类型"/>
        </el-form-item>
        <el-form-item label="学校地址" prop="schoolLocation">
          <el-input v-model="form.schoolLocation" placeholder="请输入学校地址"/>
        </el-form-item>
        <!-- 新增图片上传组件 -->
        <el-form-item label="学校风景" prop="sceneryImages">
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleImageChange"
              :on-remove="handleImageRemove"
              :file-list="fileList"
              multiple
              accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 分配学校数据权限对话框 -->
    <el-dialog :title="title" v-model="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="学校名称">
          <el-input v-model="form.schoolName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="form.schoolKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
            <el-option
                v-for="item in dataScopeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="form.dataScope == 2">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
          <el-tree
              class="tree-border"
              :data="deptOptions"
              show-checkbox
              default-expand-all
              ref="deptRef"
              node-key="id"
              :check-strictly="!form.deptCheckStrictly"
              empty-text="加载中，请稍候"
              :props="{ label: 'label', children: 'children' }"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--  导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="500px" append-to-body>
        <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的学校数据
            </div>
            <span>仅允许导入xls、xlsx格式文件</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
        </el-upload>
          <template #footer>
            <div class="el-dialog__footer">
              <el-button type="primary" @click="submitFileUpload">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
    </el-dialog>
  </div>
</template>

<script setup name="School">
import { getToken } from "@/utils/auth";
import { addSchool, dataScope, delSchool, getSchool, listSchool, updateSchool, deptTreeSelect } from "@/api/school/sm";
const router = useRouter();
const { proxy } = getCurrentInstance();

const schoolList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);
const   formatImages=(images)=> {
  if (!images) return [];
  if (Array.isArray(images)) return images;
  if (typeof images === 'string') {
    try {
      return JSON.parse(images); // 处理JSON字符串
    } catch {
      return images.split(','); // 处理逗号分隔字符串
    }
  }
  return [];
}
const getImageUrl = (url) => {
  if (!url) return [];
  //数组直接处理
  if (Array.isArray(url)) {
    return url.map(img => import.meta.env.VITE_APP_BASE_API + img);
  }
  // 字符串处理
  return import.meta.env.VITE_APP_BASE_API + url;
};
/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: "1", label: "全部数据权限" },
  { value: "2", label: "自定数据权限" },
  { value: "3", label: "本部门数据权限" },
  { value: "4", label: "本部门及以下数据权限" },
  { value: "5", label: "仅本人数据权限" }
]);
// 新增响应式数据
const fileList = ref([]);
// 新增方法 - 处理图片变化
const handleImageChange = (file, fileLists) => {
  fileList.value = fileLists.map(item => {
    if (item.raw) {
      // 为新上传的文件生成预览URL
      return {
        ...item,
        url: URL.createObjectURL(item.raw),
        uploadFile: item.raw // 保留原始文件对象用于上传
      };
    }
    return item;
  });

};

// 新增方法 - 处理图片删除
const handleImageRemove = (file, fileLists) => {
  // 释放之前创建的URL对象
  if (file.url) {
    URL.revokeObjectURL(file.url);
  }

  fileList.value = fileLists.map(item => item.raw ? {
    ...item,
    url: URL.createObjectURL(item.raw),
    uploadFile: item.raw // 保留原始文件对象用于上传
  } : item);
  // 同步更新表单中的sceneryImages字段
  form.value.sceneryImages = [];
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolName: undefined,
    schoolType: undefined,
    schoolLocation: undefined
  },
  rules: {
    schoolName: [{ required: true, message: "学校名称不能为空", trigger: "blur" }],
    schoolType: [{ required: true, message: "学校类型不能为空", trigger: "blur" }],
    schoolLocation: [{  message: "学校地址不能为空", trigger: "blur" }]
  },
});



const { queryParams, form, rules } = toRefs(data);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/sm/sm/importData"
});
/** 文件上传中处理*/
const handleFileUploadProgress= (event, file, fileList) => {
  upload.isUploading = true;
}
/** 文件上传成功处理*/
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}


/** 提交上传文件 */
function submitFileUpload(){
  proxy.$refs.uploadRef.submit();
}
/** 查询学校列表 */
function getList() {
  loading.value = true;
  listSchool(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    schoolList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const schoolIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除学校编号为"' + schoolIds + '"的数据项?').then(function () {
    return delSchool(schoolIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}
/**下载模板操作*/
function importTemplate() {
  proxy.download("sm/sm/importTemplate", {
  }, `school_${new Date().getTime()}.xlsx`);
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download("sm/sm/export", {
    ...queryParams.value,
  }, `school_${new Date().getTime()}.xlsx`);
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  menuExpand.value = false;
  menuNodeAll.value = false;
  deptExpand.value = true;
  deptNodeAll.value = false;
  form.value = {
    id: undefined,
    schoolName: undefined,
    schoolType: undefined,
    schoolLocation: undefined,
    sceneryImages: [], // 新增字段
    status: "0",
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: undefined
  };
  // 清空文件列表
  fileList.value = [];
  proxy.resetForm("schoolRef");
}
/** 添加学校 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学校";
}
/** 修改学校 */
function handleUpdate(row) {
  reset();
  const schoolId = row.id || ids.value;
  getSchool(schoolId).then(response => {
    form.value = response.data;
    // 保存原始图片数据用于比较
    form.value.originalSceneryImages = response.data.sceneryImages;
    //处理图片显示
    if(response.data.sceneryImages) {
      // 统一处理为数组形式
      const images = Array.isArray(response.data.sceneryImages)
          ? response.data.sceneryImages
          : [response.data.sceneryImages];

      fileList.value = images.map(item => {
        return {
          name: item.split('/').pop(), // 取文件名作为name
          url: getImageUrl(item),
        };
      });
    }
    form.value.schoolSort = Number(form.value.schoolSort);
    open.value = true;
    title.value = "修改学校";
  });
}/** 提交按钮 */
function submitForm() {
  proxy.$refs["schoolRef"].validate(valid => {
    if (valid) {
      //创建formData对象来处理文件上传
      const formData = new FormData();
      //添加表单数据
      console.log("form.value:",form.value)
      for(const key in form.value){
        if(form.value[key]!==undefined&& key !== 'sceneryImages'){
          formData.append(key,form.value[key]);
        }
      }
      //处理图片-新上传的文件
      fileList.value.forEach((file) => {
        if(file.raw){
          formData.append("sceneryImages", file.raw);
        }
      });
      //处理被删除的图片-从原始数据找到被删除的图片
      if (form.value.id) {
        const originalImages = formatImages(form.value.originalSceneryImages || []);
        const currentImages = fileList.value
            .filter(file => !file.raw)
            .map(file => file.url.replace(import.meta.env.VITE_APP_BASE_API, ''));

        const deletedImages = originalImages.filter(img =>
            !currentImages.includes(img)
        );

        if (deletedImages.length > 0) {
          formData.append("deletedImages", deletedImages.join(','));
        }
      }
      if (form.value.id !== undefined) {
        updateSchool(formData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSchool(formData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();
</script>
